<template>
  <div class="bussiness-release">
    <van-field class="content" v-model="content" maxlength="300" show-word-limit rows="4" placeholder="请输入商机详情" type="textarea"></van-field>
    <div class="bussiness-type" @click="bussinessType.show = true">
      <span class="left">请选择商机类型</span>
      <div class="right">
        <span>{{ bussinessType.text }}</span>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="bussiness-tag" @click="toggleTagPopup">
      <span class="left">商机标签</span>
      <div class="right">
        <span class="van-ellipsis">{{ selectedLabelList.length ? selectedLabelList.join(',') : '添加标签会让更多人看到' }}</span>
        <van-icon name="arrow" />
      </div>
    </div>
    <van-uploader v-model="pictureList" :max-count="5" :after-read="afterRead" preview-size="60px" />
    <van-button color="#FE9100" block class="publish-btn" @click="saveBussiness">发布</van-button>
    <van-popup v-model="bussinessType.show" round position="bottom">
      <van-picker show-toolbar :columns="bussinessTypeListNew" @cancel="bussinessType.show = false" @confirm="confirmBussinessType" />
    </van-popup>
    <van-popup v-model="showTag" position="bottom" class="tag-popup">
      <van-search shape="round" v-model="keyword" placeholder="请输入标签名称" @input="searchTag" />
      <div class="selected-tag-list" v-if="selectedLabelList.length">
        <van-tag v-for="(item, index) in selectedLabelList" :key="index" color="#f2f3f5" text-color="#818B9D" round closeable @close="deleteTag(index)">{{ item }}</van-tag>
      </div>
      <van-checkbox-group v-model="selectedLabelList">
        <van-cell-group>
          <van-cell v-for="(item, index) in tagList" clickable :key="index" :title="`${item}`" @click="toggleTag(item, index)">
            <template #right-icon>
              <van-checkbox :name="item" ref="checkboxes" checked-color="#FE9100" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
      <van-button color="#FE9100" block class="tag-btn" @click="toggleTagPopup">确定</van-button>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { Search, Tag, Field, Button, Icon, Uploader, Toast, CheckboxGroup, Picker, Popup, CellGroup, Cell, Checkbox } from 'vant';
import { business_saveBusiness, business_getBusinessLabelList, business_getBusinessDetail, business_updateBusiness } from '@api/bussiness';
export default {
  components: {
    [CheckboxGroup.name]: CheckboxGroup,
    [CellGroup.name]: CellGroup,
    [Checkbox.name]: Checkbox,
    [Tag.name]: Tag,
    [Cell.name]: Cell,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Search.name]: Search,
    [Uploader.name]: Uploader,
    [Icon.name]: Icon,
    [Button.name]: Button,
    [Field.name]: Field
  },
  data() {
    return {
      keyword: '',
      id: this.$route.query.id ? this.$route.query.id : '',
      showTag: false,
      content: '', // 商机内容
      bussinessType: { show: false }, // 商机类型
      tagList: [],
      allTagList: [],
      selectedLabelList: [],
      pictureList: [],
      bussinessTypeListNew: []
    };
  },
  mounted() {
    this.getOSSConfig();
    this.getTagList();
    this.bussinessTypeListNew = this.bussinessTypeList.filter(item => {
      return item.id !== 0;
    });
    this.getBussinessDetail();
  },
  computed: {
    ...mapGetters(['bussinessTypeList'])
  },
  methods: {
    //获取商机详情
    async getBussinessDetail() {
      if (!this.id) return;
      let res = await business_getBusinessDetail({ businessId: this.id });
      if (res.code === 200) {
        this.content = res.data.content;
        let item = this.bussinessTypeList.find(todo => {
          return todo.id === res.data.type;
        });
        this.bussinessType = { show: false, ...item };
        this.selectedLabelList = res.data.labelList;
        this.pictureList = res.data.pictureList.map(item => {
          return { url: item };
        });
      } else {
        Toast(res.msg);
      }
    },
    //搜索标签
    searchTag(val) {
      this.tagList = this.allTagList.filter(item => {
        return item.indexOf(val) !== -1;
      });
    },
    //删除标签
    deleteTag(index) {
      this.selectedLabelList.splice(index, 1);
    },
    toggleTagPopup() {
      this.showTag = !this.showTag;
    },
    toggleTag(item, index) {
      const k = this.selectedLabelList.findIndex(todo => {
        return todo === item;
      });
      if (this.$refs.checkboxes[index].checked) {
        this.$refs.checkboxes[index].toggle();
      } else {
        if (k === -1) {
          if (this.selectedLabelList.length < 3) {
            this.$refs.checkboxes[index].toggle();
          } else {
            Toast('最多选择3个标签');
            this.$refs.checkboxes[index].toggle(false);
          }
        }
      }
    },
    async getTagList() {
      let res = await business_getBusinessLabelList({ pageNum: 1, pageSize: 999 });
      if (res.code == 200) {
        this.tagList = res.data.list;
        this.allTagList = res.data.list;
      } else {
        Toast(res.msg);
      }
    },
    afterRead(file) {
      let OSS = require('ali-oss');
      let client = new OSS({
        region: 'oss-cn-beijing',
        accessKeyId: this.OSSConfig.accessKeyId,
        accessKeySecret: this.OSSConfig.accessKeySecret,
        stsToken: this.OSSConfig.securityToken,
        bucket: this.OSSConfig.bucket
      });
      this.$loading.show();
      client
        .put(`bussiness/userid_${this.userInfo.id}/${Date.now()}.png`, file.file)
        .then(res => {
          this.$loading.hide();
          this.pictureList[this.pictureList.length - 1].url = res.url;
        })
        .catch(err => {});
    },
    confirmBussinessType(val) {
      this.bussinessType = { ...val, show: false };
    },
    async saveBussiness() {
      const { content, selectedLabelList, bussinessType, id } = this;
      const label = selectedLabelList.join(',');
      const pictureList = this.pictureList.map(item => {
        return item.url.replace('?x-oss-process=image/resize,m_fill,h_300,w_300', '');
      });
      if (!content) {
        Toast('请填写商机内容');
      } else if (!bussinessType.id) {
        Toast('请选择商机类型');
      } else if (!label) {
        Toast('请选择商机标签');
      } else {
        let res = null;
        if (id) {
          res = await business_updateBusiness({ json: 1, useRange: 2, id, status: 1, content, type: bussinessType.id, label, pictureList });
        } else {
          res = await business_saveBusiness({ json: 1, useRange: 2, status: 1, content, type: bussinessType.id, label, pictureList });
        }
        if (res.code === 200) {
          Toast('提交成功，等待审核');
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        } else {
          Toast(res.msg);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.bussiness-release {
  padding: 30px 28px;
  box-sizing: border-box;
}
.bussiness-type {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  line-height: 80px;
  font-size: 28px;
  color: #121c32;
  padding: 0 24px;
  margin: 20px 0;
  border-radius: 6px;
  .right {
    display: flex;
    align-items: center;
    font-size: 26px;
    color: #818b9d;
  }
  i {
    margin-left: 10px;
  }
}
.content {
  padding: 12px 24px;
}
.bussiness-tag {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  height: 88px;
  padding: 0 24px;
  border-radius: 10px;
  color: #121c32;
  font-size: 28px;
  .right {
    display: flex;
    align-items: center;
    color: #818b9d;
    font-size: 26px;
    i {
      margin-left: 10px;
    }
    .van-ellipsis {
      width: 400px;
      text-align: right;
      margin-right: -10px;
    }
  }
}
/deep/ .van-uploader {
  margin: 20px 0 100px;
  .van-uploader__upload {
    background: #fff;
  }
}
.publish-btn {
  font-size: 30px;
  font-weight: bold;
  box-shadow: 0px 12px 28px 1px rgba(254, 145, 0, 0.3);
  border-radius: 6px;
}

.tag-popup {
  min-height: 100vh;
  padding: 110px 30px 140px;
  box-sizing: border-box;
  .van-cell-group {
    &:after {
      border: none;
    }
    .van-cell {
      padding: 20px 0;
      &:after {
        left: 0;
      }
    }
  }
  .van-search {
    position: fixed;
    top: 0;
    left: 30px;
    right: 30px;
    padding: 20px 0 20px;
    z-index: 100;
  }
  .selected-tag-list {
    margin-top: 10px;
    span {
      margin: 0 20px 20px 0;
    }
  }
}
.tag-btn {
  position: fixed;
  bottom: 30px;
  left: 30px;
  right: 30px;
  width: calc(100% - 60px);
  font-size: 30px;
  font-weight: bold;
  border-radius: 6px;
}
</style>
